const gulp = require('gulp')
const pug = require("gulp-pug")
const stylus = require('gulp-stylus')
const connect = require('gulp-connect')
const autoprefixer = require('gulp-autoprefixer')
const babel = require('gulp-babel')
const proxy = require('http-proxy-middleware')
const opn = require('opn')

gulp.task('build:lib', function() {
  gulp.src([
    'node_modules/jquery/dist/jquery.js',
    'node_modules/three/build/three.js',
    'node_modules/@tweenjs/tween.js/src/Tween.js',
    'node_modules/moment/min/moment-with-locales.js',
    'node_modules/handlebars/dist/handlebars.js',
    'node_modules/echarts/dist/echarts.js',
    'node_modules/d3/build/d3.js',
    'node_modules/requirejs/require.js',
    'node_modules/babel-polyfill/dist/polyfill.min.js',
    'src/lib/*',
  ]).pipe(gulp.dest('dist/lib'))

  gulp.src('src/font/*')
    .pipe(gulp.dest('dist/font'))

  gulp.src('src/js/@(jquery.jedate|world).js')
    .pipe(gulp.dest('dist/js'))

  gulp.src('src/favicon.ico')
    .pipe(gulp.dest('dist'))
})

gulp.task('build:html', function() {
  gulp.src('src/tpl/index.pug')
    .pipe(pug())
    .pipe(gulp.dest('dist'))
    .pipe(connect.reload())
})

gulp.task('build:image', function() {
  gulp.src('src/img/**/*')
    .pipe(gulp.dest('dist/img'))
    .pipe(connect.reload())
})

gulp.task('build:style', function() {
  gulp.src('src/styl/*.styl')
    .pipe(stylus())
    .pipe(autoprefixer())
    .pipe(gulp.dest('dist/css'))
    .pipe(connect.reload())

  gulp.src('src/styl/*.css')
    .pipe(gulp.dest('dist/css'))
    .pipe(connect.reload())
})

gulp.task('build:script', function() {
  gulp.src(['src/js/!(@(jquery.jedate|world)).js'])
    .pipe(babel({
      presets: ['env']
		}))
    .pipe(gulp.dest('dist/js'))
    .pipe(connect.reload())
})

gulp.task('connect', function() {
  connect.server({
    root: 'dist',
    port: 2056,
    livereload: true,
      middleware: () => [
        proxy('/api', {
          target: 'http://180.97.15.173:2059',
          //target: 'http://192.168.3.2:2059',
          changeOrigin: true
        }),
      ]
  })
  opn('http://localhost:2056/')
})

gulp.task('build', [
  'build:lib',
  'build:html',
  'build:image',
  'build:style',
  'build:script',
])

gulp.task('watch', function(){
  gulp.watch('src/tpl/**', ['build:html'])
  gulp.watch('src/img/**', ['build:image'])
  gulp.watch('src/styl/**', ['build:style'])
  gulp.watch('src/js/**', ['build:script'])
})

gulp.task('dev', ['build', 'connect', 'watch'])

